<?php
/**
 * A simple tag cloud
 * 
 * @author Magnus Stoveland <mstoveland@gmail.com>
 */
require_once("Info.php");
require_once("Tag.php");

class TagCloud {
    
    // Change these font sizes if you will
    var $max_size = 250; // max font size in %
    var $min_size = 100; // min font size in %

    function getCloud() {
        $tags = $this->getTopTags();
        return $this->calculateSizes($tags);
    }
    
    /**
     * Get data from the tags table
     * 
     * @return array $tags
     */
    function getTopTags() {
        $file = "./cache/topTags.serialized";
        if (@fopen($file, "r")) {
            return unserialize(file_get_contents($file));
        }
        $xml = file_get_contents("http://ws.audioscrobbler.com/2.0/?method=tag.getTopTags&api_key=519681edb551a3b5177bb67352e16136");
        $sxml = new SimpleXMLElement($xml);
        $sxml = $sxml->toptags;
        $i = 0;
        foreach($sxml->tag as $obj) {
        	if($obj->name != "seen live") {
	            $tag = new Tag();
	            $tag->name = (string)$obj->name;
	            $tag->count = (integer)$obj->count;
	            $output[] = $tag;
	            if($i > 16) {
	                break;
	            }
	            $i++;
        	}
        }
        shuffle($output);
        $fp = @fopen($file, "w");
        if($fp) {
            $result = fwrite($fp, serialize($output));
        }
        fclose($fp);
        return $output;
    }
    
    /**
     * Calculate sizes of each tag
     *
     * @param array &$tags
     */
    function calculateSizes($tags) {
        // Set the largest and smallest array values
        foreach($tags as $tag) {
            $weights[] = $tag->count;
        }
        $max_hits = max(array_values($weights));
        $min_hits = min(array_values($weights));
        $spread = $max_hits - $min_hits;
        if ($spread == 0) { // We don't want to divide by zero
            $spread = 1;
        }
        $step = ($this->max_size - $this->min_size)/($spread);
        foreach($tags as $id => $tagObj) {
            $size = round($this->min_size + (($tagObj->count - $min_hits) * $step));
            $tags[$id] = array("name" => $tags[$id]->name, "size" => $size);
        }
        return $tags;
    }
}
?>